package com.ouman.luoliluoli;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ouman.luoliluoli.articlefragments.DailyFeedsFragment;
import com.ouman.luoliluoli.galleryfragments.HotGirlsFragment;
import com.ouman.luoliluoli.galleryfragments.MeiziFragment;
import com.ouman.luoliluoli.galleryfragments.UnsplashFragment;
import com.ouman.luoliluoli.mainfragments.HotFragment;
import com.ouman.luoliluoli.mainfragments.LuoliTalkFragment;
import com.ouman.luoliluoli.models.UserInfo;
import com.ouman.luoliluoli.moviefragments.NewestMovieFragment;
import com.ouman.luoliluoli.moviefragments.TelevisionFragment;
import com.ouman.luoliluoli.preferences.SettingsActivity;
import com.ouman.luoliluoli.utils.GlobalConstants;
import com.ouman.luoliluoli.utils.LocalSaveHelper;
import com.ouman.luoliluoli.utils.NetworkHelper;
import com.ouman.luoliluoli.utils.ThemeChanger;
import com.ouman.luoliluoli.utils.VendorAppHelper;

import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import petrov.kristiyan.colorpicker.ColorPicker;

import static android.widget.Toast.LENGTH_SHORT;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, HotFragment.OnFragmentInteractionListener, ArticleFragment.OnFragmentInteractionListener ,
SearchFragment.OnFragmentInteractionListener, AroundFragment.OnFragmentInteractionListener, DailyFeedsFragment.OnFragmentInteractionListener,
        MeiziFragment.OnFragmentInteractionListener, UnsplashFragment.OnFragmentInteractionListener, UserFragment.OnFragmentInteractionListener,
UserInfoFragment.OnFragmentInteractionListener, DaysFragment.OnFragmentInteractionListener, DaysBlankFragment.OnFragmentInteractionListener,
        HotGirlsFragment.OnFragmentInteractionListener, MovieFragment.OnFragmentInteractionListener, NewestMovieFragment.OnFragmentInteractionListener,
        TelevisionFragment.OnFragmentInteractionListener, LuoliSquareFragment.OnFragmentInteractionListener, MainFragment.OnFragmentInteractionListener,
        LuoliTalkFragment.OnFragmentInteractionListener{

    private FloatingActionButton mainFab;

    private ImageView imageViewAvatar;
    private TextView textViewName;
    private TextView textViewSign;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private String userId;

    private UserInfo userInfo;
    private NetworkHelper networkHelper;
    private LocalSaveHelper localSaveHelper;
    private String STORAGE_NAME = "userInfo";
    private NavigationView navigationView;

    private String userGenderFlag = "default";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ThemeChanger.applyTheme(this, null);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_main);
        setSupportActionBar(toolbar);
//        getSupportActionBar().setTitle("首页");
        getSupportActionBar().setElevation(16);
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsingLayoutMain);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                new MainFragment()).commit();


        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        userId = preferences.getString("userId", "null");
        System.out.println("get user id: === " + userId);
        networkHelper = new NetworkHelper();
        if (!userId.equals("null") && NetworkHelper.isConnect(MainActivity.this)){
            // 如果有user id就去获取用户信息，没有就算了,同时要保证网络有链接
            new Thread(threadGetUserInfo).start();
        }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main, new HotFragment()).commit();
        }

        mainFab = (FloatingActionButton) findViewById(R.id.fabMain);
        mainFab.show();


        //实现drawer布局
        final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                try{
                    imageViewAvatar = (ImageView) drawer.findViewById(R.id.navAvatar);
                    imageViewAvatar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(MainActivity.this, UserActivity.class);
                            MainActivity.this.startActivity(intent);
                        }
                    });
                } catch (NullPointerException e){
                    System.out.println(e);
                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {
                final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                int colorAccent = preferences.getInt("currentThemeColorAccent", ResourcesCompat.getColor(getResources(), R.color.colorAccent, null));

                imageViewAvatar = (ImageView) drawer.findViewById(R.id.navAvatar);
                textViewName = (TextView) drawer.findViewById(R.id.textViewName);
                textViewSign = (TextView) drawer.findViewById(R.id.textViewSign);
                textViewSign.setTextColor(colorAccent);
                userInfo = new UserInfo();
                try {
                    userInfo = localSaveHelper.readUserInfoFromInternalStorage(MainActivity.this, STORAGE_NAME);
                    if (userInfo != null){
                        // 说明本地有数据，那就显示数据把
                        System.out.println("获取到了本地数据");
                        textViewName.setText(userInfo.getNickName());
                        textViewSign.setText(userInfo.getSign());
                        Glide.clear(imageViewAvatar);
                        Glide.with(MainActivity.this)
                                .load(userInfo.getAvatarUrl())
                                .asBitmap()
                                .error(R.drawable.avatar1)
                                .into(imageViewAvatar);
                    }
                } catch (IOException e){
                    Log.e("io exception ", e.getMessage());
                } catch (NullPointerException e){
                }
            }
        });
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        //设置默认的选中nav item
        navigationView.setCheckedItem(R.id.nav_home);
        navigationView.setNavigationItemSelectedListener(this);

        saveThemeColors();

    }

    private void saveThemeColors(){
        // 把当前主题的颜色都保存到本地，其他地方色彩统一化用得到

        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        TypedValue typedValue = new TypedValue();
        this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
        System.out.println("save currentThemeColorPrimary color: " + typedValue.data);
        editor.putInt("currentThemeColorPrimary", typedValue.data);

        this.getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
        System.out.println("save currentThemeColorPrimaryDark color: " + typedValue.data);
        editor.putInt("currentThemeColorPrimaryDark", typedValue.data);

        this.getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
        System.out.println("save currentThemeColorAccent color: " + typedValue.data);
        editor.putInt("currentThemeColorAccent", typedValue.data);
        editor.apply();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            MainActivity.this.startActivity(intent);
            return true;
        }else if (id == R.id.action_about){
            Intent intent = new Intent(MainActivity.this, AboutActivity.class);
            MainActivity.this.startActivity(intent);
            return true;
        } else if(id == R.id.action_join_group){
            if (VendorAppHelper.isQQAvailable(MainActivity.this)){
                String url11 = "mqqwpa://im/chat?chat_type=group&uin=366590979&version=1";
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url11)));
            } else{
                Toast.makeText(MainActivity.this, "本机貌似没有安装QQ",Toast.LENGTH_SHORT).show();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new MainFragment()).commit();
        } else if (id == R.id.nav_article) {

            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new ArticleFragment()).commit();
        } else if (id == R.id.nav_movie) {

            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new MovieFragment()).commit();
        } else if (id == R.id.nav_square) {

            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new LuoliSquareFragment()).commit();
        } else if (id == R.id.nav_gallery) {

            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new GalleryFragment()).commit();
        } else if (id == R.id.nav_search) {

            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new SearchFragment()).commit();
        } else if (id == R.id.nav_days) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new DaysFragment()).commit();

        } else if (id == R.id.nav_about) {
            Intent intent = new Intent(MainActivity.this, AboutActivity.class);
            MainActivity.this.startActivity(intent);

        } else if (id == R.id.nav_user) {
            // 判断一下，如果已经登陆了就显示UserIno，如果没有登陆就显示登陆注册页面
            Intent intent = new Intent(MainActivity.this, UserActivity.class);
            MainActivity.this.startActivity(intent);
        } else if (id == R.id.nav_theme){
            // 更改颜色
            final ThemeChanger themeChanger = new ThemeChanger(MainActivity.this);
            final ColorPicker colorPicker = new ColorPicker(MainActivity.this);
            final HashMap themeColorMap = themeChanger.themeColorMap;
            ArrayList<String> colors = new ArrayList<>(themeColorMap.values());
            final ArrayList<Integer> styles = new ArrayList<>(themeColorMap.keySet());

            colorPicker.setColors(colors).setDefaultColorButton(Color.parseColor("#f84c44")).setColumns(5).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
                @Override
                public void onChooseColor(int position, int color) {
                    System.out.println("position: " + position);
                    if (position == -1){
                        Toast.makeText(MainActivity.this, "未选择颜色哦", Toast.LENGTH_SHORT).show();
                    }else {
                        themeChanger.applyTheme(MainActivity.this, styles.get(position));
                    }
                }

                @Override
                public void onCancel() {

                }
            }).setRoundColorButton(true)
                    .setTitle("选择你喜欢的颜色").show();
        } else if (id == R.id.nav_settings){
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            MainActivity.this.startActivity(intent);
        } else if (id == R.id.nav_sponse){
            Intent intent = new Intent(MainActivity.this, SponsorActivity.class);
            MainActivity.this.startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
        drawer.closeDrawer(GravityCompat.START);
        return true;

    }

    // 显示或者隐藏fab button
    public void hideFloatingActionButton(){
        mainFab.hide();
    }
    public void showFloatingActionButton(){
        mainFab.show();
    }

    // 获取main的appbar layout设置elevation
    public void setAppBarElevation(float elevation){
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        appBarLayout.setElevation(elevation);
    }

    // disable collapsing layout title
    public void disableCollapsingLayoutTitle(){
        collapsingToolbarLayout.setTitleEnabled(false);
    }
    public FloatingActionButton getFloatingActionButton(){
        return mainFab;
    }
    //实现fragment监听方法
    public void onFragmentInteraction(Uri uri){

    }

    // 添加一个网络请求，做的事情非常简单，就是在navigation drawer中显示用户信息
    private  Thread threadGetUserInfo = new Thread(){
        public void run(){
            HttpURLConnection connection = null;
            try {
                GlobalConstants globalConstants = new GlobalConstants();
                // user_id=user_id
                String urlAPI = globalConstants.API_USER + "?user_id=" + userId;
                System.out.println(urlAPI);
                URL url = new URL(urlAPI);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();
                    JSONObject jsonObject = new JSONObject(result);
                    String status = jsonObject.getString("status");
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (status.equals("success")){
                        // 表示user id获取信息成功
                        String userName = data.getString("user_name");
                        String userSign = data.getString("user_sign");
                        String userGender = data.getString("user_gender");
                        String userBirth = data.getString("user_birth");
                        String userEmail = data.getString("user_email");
                        String userAvatarUrl = globalConstants.API_BASE_URL + data.getString("user_avatar_url");
                        userInfo = new UserInfo();
                        userInfo.setNickName(userName);
                        userInfo.setSign(userSign);
                        userInfo.setGender(userGender);
                        userInfo.setBirthday(userBirth);
                        userInfo.setEmail(userEmail);
                        userInfo.setAvatarUrl(userAvatarUrl);

                        userGenderFlag = userGender;
                        Message msg = Message.obtain();
                        msg.what = 0;
                        handler.sendMessage(msg);

                    } else{
                        // 获取user id信息失败
                        Message msg = Message.obtain();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }

                }
            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            if (msg.what == 0){
                // 表示成功获取到数据
                // 这里不进行UI操作，只是把userInfo保存到本地
                // 在这里我们不需要读取本地数据，直接覆盖即可
                localSaveHelper = new LocalSaveHelper();
                System.out.println("初始化了saver。 from Main");
                localSaveHelper.saveToInternalStorage(userInfo, "userInfo", MainActivity.this, Context.MODE_PRIVATE);
                System.out.println("user info save to local success!!!");

                Menu menuNav = navigationView.getMenu();
                int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                if (userGenderFlag.equals("default") || userGenderFlag.equals("男") && (hour > 21 || hour < 5)){
                    System.out.println("这个时候妹子是可见");
                    menuNav.findItem(R.id.nav_gallery).setVisible(true);
                }else{
                    menuNav.findItem(R.id.nav_gallery).setVisible(false);
                }
            }else if (msg.what == 1){
                Toast.makeText(MainActivity.this, "获取用户信息失败", LENGTH_SHORT).show();
            }
        }
    };


}
